package com.winchain.chainbill.bill.biz.repurchase.cmd;

import com.shell.bee.acct.transaction.po.AcctTxRec;
import com.shell.bee.base.utils.DateUtil;
import com.shell.bee.base.utils.SystemUtil;
import com.shell.framework.command.CallbackContext;
import com.shell.framework.command.ICallback;
import com.winchain.chainbill.bill.base.po.CbRcv;
import com.winchain.chainbill.bill.base.po.CbRec;
import com.winchain.chainbill.bill.base.po.CbRpur;
import com.winchain.chainbill.bill.base.service.CbRcvService;
import com.winchain.chainbill.bill.biz.Bill;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class BillRcv4RpurCmd implements ICallback<Bill<CbRpur>, AcctTxRec> {
	@Autowired
	private CbRcvService cbRcvService;

	public boolean callback(CallbackContext<Bill<CbRpur>, AcctTxRec> context) throws Exception {
		CbRec record = ((Bill) context.getSource()).getRec();
		CbRpur cbRpur = (CbRpur) ((Bill) context.getSource()).getSource();

		CbRcv cbRcv = getRcv(record);
		cbRcv.setRcvLvl(cbRpur.getHldrLvl());
		cbRcv.setTxId(cbRpur.getRpurId());
		this.cbRcvService.saveOrUpdate(cbRcv);
		return false;
	}

	private CbRcv getRcv(CbRec record) {
		CbRcv cbRcv = new CbRcv();
		cbRcv.setBillId(record.getBillId());
		cbRcv.setRcvState("2");

		cbRcv = (CbRcv) this.cbRcvService.selectOne(cbRcv);
		CbRcv resultRcv = new CbRcv();
		if (cbRcv != null) {
			cbRcv.setRcvState("-2");
			this.cbRcvService.updateNotNull(cbRcv);

			BeanUtils.copyProperties(cbRcv, resultRcv);
			resultRcv.setRcvState("2");
			resultRcv.setRcvId(SystemUtil.getUUID());
			resultRcv.setBillId(record.getBillId());
			resultRcv.setOptSeq(Integer.valueOf(0));
			resultRcv.setRemark("������������");
			resultRcv.setTxType("4");
			resultRcv.setCreateTime(DateUtil.getSystemDateTime());
		} else {
			resultRcv.setBillId(record.getPrntId());
			resultRcv.setRcvState("2");
			resultRcv = (CbRcv) this.cbRcvService.selectOne(resultRcv);
			resultRcv.setRcvId(SystemUtil.getUUID());
			resultRcv.setBillId(record.getBillId());
			resultRcv.setOptSeq(Integer.valueOf(0));
			resultRcv.setRemark("������������");
			resultRcv.setTxType("4");
			resultRcv.setCreateTime(DateUtil.getSystemDateTime());
		}
		return resultRcv;
	}
}
